import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '@/views/Login/login.vue'
import Layout from '@/views/layout/index.vue'
import store from '@/store'
// import Home from '@/views/layout/Home/index.vue'
const Home = () => import('@/views/layout/Home/index.vue')
// import UserAvatar from '@/views/layout/User/userAvatar.vue'
const UserAvatar = () => import('@/views/layout/User/userAvatar.vue')
// import UsrePwd from '@/views/layout/User/userPwd.vue'
const UsrePwd = () => import('@/views/layout/User/userPwd.vue')
// import Artcate from '@/views/layout/Article/ArtCate.vue'
const Artcate = () => import('@/views/layout/Article/ArtCate.vue')
// import ArtList from '@/views/layout/Article/ArtList.vue'
const ArtList = () => import('@/views/layout/Article/ArtList.vue')
// import _404 from '@/views/layout/404/404.vue'
const _404 = () => import('@/views/layout/404/404.vue')
// import UserInfo from '@/views/layout/User/uderInfo.vue'
const UserInfo = () => import('@/views/layout/User/uderInfo.vue')
// import Register from '@/views/Register/register.vue'
const Register = () => import('@/views/Register/register.vue')

Vue.use(VueRouter)

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  return originalPush.call(this, location).catch(err => err)
}

// 把下面的代码粘贴到路由模块中对应的位置，即可防止路由报错的问题
const originalReplace = VueRouter.prototype.replace
VueRouter.prototype.replace = function replace(location) {
  return originalReplace.call(this, location).catch(err => err)
}

const routes = [
  { path: '/register', component: Register, meta: { title: '注册' } },
  { path: '/login', component: Login, meta: { title: '登录' } },
  {
    path: '/',
    component: Layout,
    redirect: '/home',
    meta: { title: '首页' },
    children: [
      { path: 'home', component: Home, meta: { title: '首页' } },
      { path: 'user-info', component: UserInfo, meta: { title: '基本资料' } },
      { path: 'user-avatar', component: UserAvatar, meta: { title: '更换头像' } },
      { path: 'user-pwd', component: UsrePwd, meta: { title: '重置密码' } },
      { path: 'art-cate', component: Artcate, meta: { title: '文章分类' } },
      { path: 'art-list', component: ArtList, meta: { title: '文章列表' } }

    ]
  },
  { path: '/*', component: _404, meta: { title: '404' } }
]

const router = new VueRouter({
  routes// 必须是路由规则的数组
})

const whiteList = ['/login', '/register', '/404']
// 路由的全局前置守卫，所有的路由跳转前都要经过这里
router.beforeEach((to, from, next) => {
  // 1、获取token
  const { token } = store.state.user
  // 给页面命名
  document.title = to.meta.title

  if (token) {
    // 2.根据有无token，决定是否放行
    next()
  } else { // 没有token
    if (whiteList.includes(to.path)) {
      next()// 直接放行
    } else {
      next('/login')// 要去首页，先去登录页
    }

    /* if (to.path === '/') { // 要去首页，先登录
      next('/login')
    } else { // 登录页或者注册页直接放行
      next()
    } */
  }
})

export default router
